package com.netty.server.pool;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.qbb.server.aop.QbbServerAopUtil;
import com.qbb.server.bean.read.SocketBean;
import com.qbb.server.bean.result.SocketResultBean;
import com.qbb.server.bean.result.SocketResultMapBean;
import com.qbb.server.exception.HandlerException;
import com.qbb.server.security.SecurityUtil;
import com.qbb.server.util.DateUtil;

/**
 * @author 作者 : 陈怀傲
 * @version 创建时间：2015年4月14日 下午2:51:45 类说明
 */
public class ThreadChannelCall {
	private static Log log = LogFactory.getLog(ThreadChannelCall.class);

	private ThreadChannelBean channelBean;

	private ThreadChannelCall() {
	}

	public ThreadChannelCall(ThreadChannelBean channelBean) {
		this.channelBean = channelBean;
	}

	public void execute() {
		final ChannelHandlerContext ctx = channelBean.getCtx();

		SocketBean socketBean = null;
		String descurityStr = null;

		try {
			Object msg = channelBean.getMsg();

			String uuidStr = null;
			try {
				socketBean = SocketBean.getSocketBean(msg);
				uuidStr = socketBean.getUuIdStr();
				uuidStr = uuidStr != null ? uuidStr : "";
			} catch (Exception e) {
				HandlerException.error(e);
			}
			SocketResultBean resultBean = null;
			try {
				if (socketBean != null) {
					resultBean = QbbServerAopUtil.getResult(socketBean);
				}
			} catch (Exception e) {
				HandlerException.error(e);
			}

			try {
				if (resultBean == null) {
					resultBean = new SocketResultMapBean();
				}
			} catch (Exception e) {
				HandlerException.error(e);
			}

			String returnStr = null;
			try {
				returnStr = uuidStr + "|" + resultBean.toString();
			} catch (Exception e) {
				HandlerException.error(e);
			}

			try {
				String finalStr = SecurityUtil.getFinalStr(returnStr);
				descurityStr = SecurityUtil.getSecurityStr(finalStr,
						SecurityUtil.kek, 0);
			} catch (Exception e) {
				HandlerException.error(e);
			}

		} catch (Exception e) {
			HandlerException.error(e);
		} finally {
			if (descurityStr == null) {
				descurityStr = "";
			}
			final ChannelFuture f = ctx.write(descurityStr); // (3)
			ctx.flush();

			f.addListener(new ChannelFutureListener() {
				public void operationComplete(ChannelFuture future) {
					assert f == future;
					ctx.close();
				}
			}); // (4)

			Date endDate = new Date();
			String endStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(endDate);
			log.info("QbbServer channelRead end[" + endStr + "]");
		}
	}
}
